import cv2
import numpy as np
import math

cap = cv2.VideoCapture(0)

while(1):
    ret,frame = cap.read()
    frame = cv2.flip(frame,1)
    img1 = cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)
    img2 = cv2.cvtColor(img1,cv2.COLOR_BGR2GRAY)
    #w,h,c= img2.shape  #宽、高、通道

    #yellow HSV颜色范围
    loyell = np.array([32,50,40])
    upyell = np.array([37,255,255])
    
    maskyell = cv2.inRange(img1,loyell,upyell)  #找到黄色  后面预计将对maskyell进行处理 
    resyell = cv2.bitwise_and(frame,frame,mask = maskyell) #提取黄色区域  


    kernel = np.ones((5,5),np.uint8)
    '''
    img_mean = cv2.blur(maskyell, (5,5))#均值
    img_mean = cv2.morphologyEx(img_mean,cv2.MORPH_OPEN,kernel)
    img_Guassian = cv2.GaussianBlur(maskyell,(5,5),0)#高斯
    img_Guassian = cv2.morphologyEx(img_Guassian,cv2.MORPH_OPEN,kernel)
    '''
    img_median = cv2.medianBlur(maskyell, 5)#中值
    img_median = cv2.morphologyEx(img_median,cv2.MORPH_OPEN,kernel)    ##效果最好
    '''
    img_bilater = cv2.bilateralFilter(maskyell,9,75,75)#双边
    img_bilater = cv2.morphologyEx(img_bilater,cv2.MORPH_OPEN,kernel)
    '''


    #提取轮廓后，拟合外接多边形
    contyell,heiryell = cv2.findContours(img_median,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
    print("len(contours) = %d"%(len(contyell)))
    
    #提取面积最大轮廓 多边形逼近
    if contyell != []:
    
        cntyell = contyell[0]
        max_yell = cv2.contourArea(cntyell)

        for conty in contyell:
            if cv2.contourArea(conty) > max_yell:
                max_yell = cv2.contourArea(conty)
                cntyell = conty

        perimeteryell = cv2.arcLength (cntyell,True)
        epsilonyell = 0.03*cv2.arcLength(cntyell,True)
        approxyell = cv2.approxPolyDP(cntyell,epsilonyell,True)

        
        if approxyell.size < 9:
            #cv2.drawContours(frame,cntyell,-1,(0,249,225),3)
            cv2.drawContours(frame,approxyell,-1,(0,0,0),8)
            cv2.polylines (frame,[approxyell],True,(255,0,0),3)

                

        #cv2.drawContours(frame,cntyell,-1,(0,249,225),3)
        cv2.drawContours(frame,approxyell,-1,(0,0,0),3)

    else  :
        approxyell = np.array([[[0,0]]],dtype=np.int32)
        cntyell = []
        
        



    
    cv2.imshow('respyell',resyell)
    cv2.imshow('maskyell',maskyell)       
    cv2.imshow('frame',frame)
    '''
    cv2.imshow('img_mean',img_mean)
    cv2.imshow('img_Guassian',img_Guassian)
    '''
    cv2.imshow('img_median',img_median)
    '''
    #模糊滤波+形态学开运算
    cv2.imshow('img_bilater',img_bilater)
    

    #二值图像
    ret, binary = cv2.threshold(img_median, 90, 255, cv2.THRESH_BINARY)
    cv2.imshow("bb", binary)
    
    
 
    # canny边缘检测  后面提取轮廓 拟合外接多边形。。。面积？？
    canny = cv2.Canny(img_median,0,60,apertureSize = 3)
    cv2.imshow("canny",canny)
    '''



    k = cv2.waitKey(1) & 0xFF
    if k == ord('q'):
        break
  


cap.release()
cv2.destroyAllWindows()

















